-- UINewAirShipStrengthen
-- Created by dengc May/11/2016
-- 飞艇改造界面

require "game/ui/form/item/UIItemCompound"

-- UINewAirShipStrengthen继承自Layer
UINewAirShipStrengthen = class("UINewAirShipStrengthen", function()
    return cc.Layer:create();
end);

function UINewAirShipStrengthen.create(id)
    return UINewAirShipStrengthen.new(id);
end

local MAX_REMAKE_GROUP = 5; -- 最大改造组数

-- 声明
local resize;


-- 构造函数
function UINewAirShipStrengthen:ctor(id)
    -- 初始化
    self:setName("UINewAirShipStrengthen");
    local node = cc.CSLoader:createNode("layout/sky_city/NewAirShipStrengthen.csb");
    self:addChild(node);
    self.node = node;
    self.id = id;

    -- 注册事件处理的回调函数
    self:registerEventCallback();

    -- 初始化窗口
    self:initForm();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 初始化窗口
function UINewAirShipStrengthen:initForm()
    -- 隐藏节点
    for  i = 1, 5 do
        local rank = findChildByName(self.node, "CT/rank" .. i);
        local line = findChildByName(self.node, "CT/line" .. i);
        rank:setVisible(false);
        line:setVisible(false);
    end

    -- 设置飞艇缩略图
    local airShipIcon = findChildByName(self.node, "CT/airship_icon");
    local airShipPath = getAirShipImgPath(self.id);
    airShipIcon:loadTexture(airShipPath);
    airShipIcon:setScale(0.6);

    -- 设置飞艇背景
    local airShipBg = findChildByName(self.node, "CT/bg_main");
    airShipBg:loadTexture(airShipPath);
    airShipBg:setPosition(airShipBg:getPositionX() - 10, airShipBg:getPositionY() -40);
    airShipBg:setScale(1.2);
    airShipBg:setOpacity(30);
end

-- 重绘
function UINewAirShipStrengthen:redraw()
    -- 载入标题
    local title = findChildByName(self.node, "CT/title");
    local title2 = findChildByName(self.node, "CT/title2");

    -- 根据飞艇信息设置标题
    local name = NewAirShipM.query(self.id, "name");
    title:setString(name);
    title2:setString(string.format(getLocStr("device_remould"),
        NewAirShipM.getAirShipStrengtenTimes(self.id), NewAirShipM.getCurMaxStrengthenLevel(self.id)));
    TextStyleM.setTitleStyle2(title);
    TextStyleM.setSubheadStyle(title2);

    -- 绘制飞艇改造部件
    self:redrawAirShipParts();

    -- 尝试提示进阶
    self:tryShowHint();
end

-- 尝试提示进阶
function UINewAirShipStrengthen:tryShowHint()
    local btnUpRank = findChildByName(self.node, "BT/btn_up_rank");
    local hintNode = findChildByName(btnUpRank, "hint_node");
    checkBlueBubbleStatus(hintNode, NewAirShipM.canUpRank(self.id));
end

-- 绘制飞艇改造部件
function UINewAirShipStrengthen:redrawAirShipParts()
    -- 隐藏顶部菜单
    local topMenu = UIMgr.getCurrentScene().topMenu;
    if topMenu then
        UIMgr.getCurrentScene().topMenu:setVisible(false);
    end

    local rank = NewAirShipM.getAirShipRank(self.id);
    local strengthenRecord = NewAirShipM.getStrengthenRecord(self.id) or {};
    self.rank = rank;
    self.strengthenRecord = strengthenRecord;

    -- 计算可以显示的改造项组数
    local num = NewAirShipM.getShowGroup(self.id);
    -- 锁的星数
    local starNum = num + 1;

    for i = 1, num do
        local group = findChildByName(self.node, "CT/rank" .. i);
        local line = findChildByName(self.node, "CT/line" .. i);
        group:setVisible(true);
        line:setVisible(true);

        local endNum = i * 4;
        local startNum = endNum - 3;

        for j = startNum, endNum do
            -- 对应节点
            local pos = group:getChildByName("pos" .. j);

            -- 先移除所有的子节点
            pos:removeAllChildren();

            local needOpacity = false;
            if strengthenRecord and table.indexOf(strengthenRecord, j) == -1 then
                needOpacity = true;
            end

            -- 获取强化项目(目前只支持一个)
            local item = NewAirShipM.queryStrengthen(self.id, j)[1];
            local classId = item[2];
            if classId ~= nil then
                -- 绘制装置
                self:redrawDeviceItem(pos, classId, needOpacity, j);
            end
        end
    end

    -- 在下一组的首个位置上放置下一等级飞艇图标
    if num < MAX_REMAKE_GROUP then
        local nextGroup = findChildByName(self.node, "CT/rank" .. tostring(num + 1));
        local posNum = 1 + num * 4;
        local posNode = nextGroup:getChildByName("pos" .. posNum);

        local airShipNode = cc.CSLoader:createNode("layout/combat_stat/CombatStatItem.csb");
        local icon = airShipNode:getChildByName("icon");
        local star = airShipNode:getChildByName("star");

        -- 先移除所有的子节点
        posNode:removeAllChildren();

        -- 隐藏数量和背景
        local bg = airShipNode:getChildByName("bg");
        local num = airShipNode:getChildByName("num");
        bg:setVisible(false);
        num:setVisible(false);

        local lockPath = "images/ui/hero/lock.png";
        icon:loadTexture(lockPath);
        icon:setScale(0.9);

        local tStar = createStarLayer(starNum, "images/ui/symbol/star_little.png", "center", -0.7);
        if tStar ~= nil then
            star:addChild(tStar);
        end
        -- 星星上移
        star:setPositionY(star:getPositionY() + 10);
        nextGroup:setVisible(true);
        posNode:addChild(airShipNode);

        -- 记录下显示锁的对象
        self.lockNode = airShipNode;

        icon:setTouchEnabled(true);

        icon:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                -- 飘字提示
                AudioM.playFx("button_receive_failed");

                alert(string.format(getLocStr("airship_strengthen_open"), rank + 1));
            end
        end);
    end
end

-- 绘制每一种装置
function UINewAirShipStrengthen:redrawDeviceItem(posNode, classId, needOpacity, feedId)
    local itemPath = getItemIconPath(ItemM.query(classId, "icon"));
    local maskPath = "images/ui/hero/mask.png";
    local device = cc.CSLoader:createNode("layout/combat_stat/CombatStatItem.csb");
    local icon = device:getChildByName("icon");
    local star = device:getChildByName("star");

    -- 隐藏数量和背景
    local bg = device:getChildByName("bg");
    local num = device:getChildByName("num");
    bg:setVisible(false);
    num:setVisible(false);

    -- 载入图片
    icon:loadTexture(itemPath);
    bg:loadTexture(maskPath);
    bg:setScale(0.9);

    -- 重复动画相关配置
    local initScale  = 0.9;    -- 初始模型比例
    local transScale = 1.0;    -- 过渡模型比例
    local finalScale = 1.1;    -- 最终模型比例
    local speedCoef =  1.0;    -- 速度系数

    local function playAction(image)
        local upTime    = 0.25;
        local up2Time   = 0.25/speedCoef;
        local scaleUp   = cc.ScaleTo:create(upTime, transScale);
        local scaleUp2  = cc.ScaleTo:create(up2Time, finalScale);

        local seq1 = cc.Sequence:create(scaleUp, scaleUp2);
        local action1 = cc.Spawn:create(seq1);

        -- 2.短暂停顿
        local delayTime = 0.2/speedCoef;
        local delay = cc.DelayTime:create(delayTime);

        -- 3.变小
        local downTime  = 0.25/speedCoef;
        local down2Time = 0.25/speedCoef;
        local scaleDown = cc.ScaleTo:create(downTime, transScale);
        local scaleDown2 = cc.ScaleTo:create(down2Time, initScale);
        local seq2 = cc.Sequence:create(scaleDown, scaleDown2);
        local action2 = cc.Spawn:create(seq2);

        local sequenceNodeAction = cc.Sequence:create(action1, delay, action2);
        image:runAction(cc.RepeatForever:create(sequenceNodeAction));
    end

    if (NewAirShipM.isMaterialEnough(self.id, feedId) == true or ItemM.getAmount(ME.user, classId) > 0) and needOpacity then
        -- 右上角显示加号
        local addImage = ccui.ImageView:create();
        addImage:loadTexture("images/ui/hero/add3.png");
        addImage:setPosition(cc.p(addImage:getPositionX() + 35, addImage:getPositionY() + 35));
        device:addChild(addImage);
        -- 呼吸动态
        playAction(addImage);
    elseif needOpacity then
        -- 右上角显示问号
        local ifImage = ccui.ImageView:create();
        ifImage:loadTexture("images/ui/hero/if.png");
        ifImage:setPosition(cc.p(ifImage:getPositionX() + 35, ifImage:getPositionY() + 35));
        device:addChild(ifImage);
    end

    -- 是否需要透明
    if needOpacity then
        icon:setOpacity(80);
        bg:setVisible(true);
    end

    -- 显示星星
    local starPath = "images/ui/symbol/star_little.png";
    local rank = ItemM.query(classId, "rank");
    local tStar;

    tStar = createStarLayer(rank, starPath, "center", -0.7);

    if tStar ~= nil then
        star:addChild(tStar);
    end

    -- 星星上移
    star:setPositionY(star:getPositionY() + 15);

    posNode:addChild(device);

    icon:setTouchEnabled(true);

    -- 点击处理
    icon:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if needOpacity then
                local record = NewAirShipM.getStrengthenRecord() or {};
                if table.indexOf(record, feedId) ~= -1 then
                    -- 飄字提示
                    alert(getLocStr("remould_already"));
                    AudioM.playFx("button_receive_failed");
                    return;
                end
                -- 显示食物详细信息
                local UIItemCompound = UIItemCompound.create(self.id, classId, nil, feedId);
                UIMgr.getCurrentScene():addForm(UIItemCompound);
                AudioM.playFx("ui_open1");
            else
                -- 飄字提示
                alert(getLocStr("remould_already"));
                AudioM.playFx("button_receive_failed");
            end
        end
    end);
end

-- 播放属性提升动画
function UINewAirShipStrengthen:showAttribUpEffect(feedId)
    -- 先屏蔽
    if true then
        return;
    end

    local function delay()
        local food = PetM.getFeedFood(self.id, feedId);
        local props = PetM.getFoodProp(food[2]);
        local effectNode = findChildByName(self.node, "CT");
        for i = 1, #props do
            local function show()
                local prop = props[i];
                local desc = extractString(PropM.getPropDesc(props[i]));
                -- 播放属性提升飘字特效
                playAttribUpEffect3(effectNode, cc.p(0, 50), desc);
            end
            if i == 1 then
                show();
            else
                performWithDelay(self, show, (i - 1) * 0.7);
            end
        end
    end
    performWithDelay(self, delay, 0.5);
end

-- 注册点击事件
function UINewAirShipStrengthen:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UINewAirShipStrengthen");
        end
    end
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册升阶按钮点击事件
    local btnUpRank = findChildByName(self.node, "BT/btn_up_rank");
    local function onUpRankClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local rank = NewAirShipM.getAirShipRank(self.id);
            local cost = FormulaM.invoke("CALC_AIRSHIP_UPGRADE_COST", self.id, rank);
            local chipId = NewAirShipM.query(self.id, "chip_id");

            if not cost then
                return;
            end

            if rank >= NewAirShipM.getMaxRank(self.id) then
                alert(getLocStr("airship_rank_is_max"));
                return;
            end

            local function upRank()
                local maxLevel = NewAirShipM.getCurMaxStrengthenLevel(self.id);
                if NewAirShipM.getAirShipStrengtenTimes(self.id) < maxLevel then
                    -- 弹出属性不足提示
                    alert(getLocStr("strengthen_not_enough"));
                elseif ItemM.getAmount(ME.user, chipId) < cost[chipId] then
                    -- 弹出属性不足提示
                    alert(string.format(getLocStr("chip_not_enough"), NewAirShipM.query(self.id, "name")));
                else
                    -- 升阶
                    Operation.cmd_airship_upgrade(self.id)
                end
            end

            local costNumStr = "[blue]" .. cost[chipId] .. "[-]";

            if ItemM.getAmount(ME.user, chipId) < cost[chipId] then
                costNumStr = "[red]" .. cost[chipId] .. "[-]";
            end

            local gainWay = NewAirShipM.query(self.id, "gain_way");
            local airshipName = NewAirShipM.query(self.id, "name");
            local confirmTip = string.format(getLocStr("air_ship_up_confirm"), airshipName, costNumStr, gainWay);

            -- 弹出确认界面
            confirm2(CONFIRM_TYPE_OK_CANCEL, getLocStr("air_ship_up_rank"),
                    confirmTip, upRank, nil, nil, nil, {["line_word_count"] = 20});
        end
    end
    btnUpRank:addTouchEventListener(onUpRankClick);
    TextStyleM.setTextStyle(btnUpRank, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnUpRank:setTitleText(getLocStr("air_ship_up_rank"));
end

-- 注册事件处理的回调函数
function UINewAirShipStrengthen:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UINewAirShipStrengthen 界面析构清理");
            EventMgr.removeAll("UINewAirShipStrengthen");

            -- 显示顶部
            local topMenu = UIMgr.getCurrentScene().topMenu;
            if topMenu then
                UIMgr.getCurrentScene().topMenu:setVisible(true);
            end

            -- 显示飞艇列表界面
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewAirShipList");
            if uiForm ~= nil then
                -- 显示
                uiForm:setVisible(true);

                -- 刷新下
                uiForm:redraw();
            end
        elseif ev == "enter" then
            -- 隐藏顶部
            UIMgr.getCurrentScene().topMenu:setVisible(false);

            -- 隐藏飞艇列表界面
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewAirShipList");
            if uiForm ~= nil then
                uiForm:setVisible(false);
            end
        end
    end);

    -- 玩家的飞艇属性变化
    EventMgr.register("UINewAirShipStrengthen", event.USER_INFO_UPDATED, function(args)
        if args == "airships" or args == "new_airships" then
            local rank = NewAirShipM.getAirShipRank(self.id);
            local strengthenRecord = NewAirShipM.getStrengthenRecord(self.id) or {};
            if rank ~= self.rank then

                -- 飘字
                alert(string.format(getLocStr("up_rank_successful"), NewAirShipM.query(self.id, "name")));

                -- 锁摇晃、炸开，然后重绘界面
                local lockNode = self.lockNode;
                playShakeEffect(lockNode, 0.1, 5, 1);

                local delayTime1 = cc.DelayTime:create(0.4);
                local callFunc1 = cc.CallFunc:create(function ()
                    playEffect(lockNode, 4028, -10, -10, nil, 1.5);
                end);
                local delayTime2 = cc.DelayTime:create(0.2);
                local callFunc2 = cc.CallFunc:create(function ()
                    self.lockNode = nil;
                    -- 重绘界面
                    self:redraw();
                end);
                lockNode:runAction(cc.Sequence:create(delayTime1, callFunc1, delayTime2, callFunc2));

                self.rank = rank;
            elseif #strengthenRecord > #self.strengthenRecord then
                self.newRecord = strengthenRecord;

                -- 如果合成动画页面已经关闭，需要直接刷新（正常是强化效果等合成动画页面关闭时再显示）
                if not UIMgr.getCurrentScene():isOpen("UIMaterialCompound") then
                    self:showPropUpdate();
                end
            else
                -- 重绘界面
                self:redraw();
            end
        end
    end);
end

-- 显示属性相关的更改
function UINewAirShipStrengthen:showPropUpdate()
    if type(self.newRecord) == "table" and #self.newRecord > #self.strengthenRecord then

        local strengthenRecord = self.newRecord;
        self.newRecord = {};
        -- 强化项增多
        for _, id in ipairs(strengthenRecord) do
            if table.indexOf(self.strengthenRecord, id) < 0 then
                local device = NewAirShipM.getStrengthenDevice(self.id, id);
                local classId = device[2];
                local propStr = ItemM.query(classId, "detail");

                alert(propStr);
            end
        end

        self.strengthenRecord = strengthenRecord;

        -- 重绘界面
        self:redraw();
    end
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

